package Stream流学习;

import lombok.Data;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class flatMap方法 {

    // ================ 场景1 ==========================
    // 两个列表中的元素分别要乘以10,并合并为一个列表

    @Test
    public void 场景1_方式1_使用flatMap(){
        List<Integer> array1 = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> array2 = Arrays.asList(6, 7, 8, 9, 10);

        List<List<Integer>> tempList = Arrays.asList(array1, array2);

        List<Integer> result = tempList.stream()
                .flatMap(list -> list.stream().map(integer -> integer * 10))
                .collect(Collectors.toList());

        result.stream().forEach(System.out::println);
    }

    @Test
    public void 场景1_方式2_不使用flatMap(){
        List<Integer> array1 = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> array2 = Arrays.asList(6, 7, 8, 9, 10);

        ArrayList<Integer> result = new ArrayList<>();
        result.addAll(array1.stream().map(integer -> integer * 10).collect(Collectors.toList()));
        result.addAll(array2.stream().map(integer -> integer * 10).collect(Collectors.toList()));

        result.stream().forEach(System.out::println);
    }

    // 场景2 ==============================
    // 每个人都有喜欢的明星，并且可能不止一个，把小明，小王，小李喜欢的明星合并成一个列表返回
    @Data
    private static class Person{
        private String name;
        private List<String> stars;
    }

    @Test
    public void 合并喜欢的明星(){
        Person ming = new Person();
        ming.setName("小明");
        ming.setStars(Arrays.asList("黄继光","邱少云"));
        Person wang = new Person();
        wang.setName("小王");
        wang.setStars(Arrays.asList("小鞠","小艾","陈观慧","陈思"));
        Person li = new Person();
        li.setName("小李");
        li.setStars(Arrays.asList("刘亦菲","李冰"));

        List<Person> persons = new ArrayList<>();
        persons.add(ming);
        persons.add(wang);
        persons.add(li);

        List<String> stars = persons.stream()
                .flatMap(person -> person.getStars().stream())
                .collect(Collectors.toList());
        stars.stream().forEach(System.out::println);
    }

    // 场景3 ==========================================================
    // list1中记录了数字编号
}
